<script lang="ts" setup>
import { ref, onMounted,onUnmounted,onBeforeUnmount} from 'vue'
import { ElButton, ElMessage, } from 'element-plus'
import "element-plus/theme-chalk/el-message.css"
import router from "@/router/index"
import { useUserStore } from "@/stores/user"
const userStore = useUserStore()
import { useFunctionTreeStore } from "@/stores/functionTree"
import {res} from '@/pojo/dto/res'
const base64Image = ref(null)
const videoRef = ref(null)
const showFace = ref(true)
//访问摄像头获取视频流
const setupCamera = () => {
  navigator.mediaDevices.getUserMedia({ video: true })
    .then((stream) => {
      videoRef.value.srcObject = stream
    })
    .catch((error) => {
      console.error('访问摄像头发生错误:', error)
    })
}
//关闭摄像头
const closeCamera = () => {
  if (videoRef.value) {
    const stream = videoRef.value.srcObject;
    if (stream) {
      const tracks = stream.getTracks();
      tracks.forEach(track => {
        track.stop();
      });
      videoRef.value.srcObject = null;
    }
  }
}
const capture = async () => {
  const canvas = document.createElement('canvas');
  canvas.width = videoRef.value.videoWidth
  canvas.height = videoRef.value.videoHeight
  canvas.getContext('2d').drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);

  const blobPromise = new Promise((resolve) => {
    canvas.toBlob((blob) => {
      resolve(blob);
    }, 'image/jpeg');
  });

  const blob = await blobPromise;
  const fileReader = new FileReader()
  fileReader.onloadend = async () => {
    const base64Data = fileReader.result.split(',')[1]
    console.log(base64Data)
    base64Image.value = base64Data
    const res:res = await userStore.getUserInfoByFace(base64Data)
    if(res.code==0){
      //关闭摄像头
      closeCamera()
      console.log('摄像头关闭')
    }
    if(res.code!=0){
      return
    }
    const functionTreeStore = useFunctionTreeStore()
    await functionTreeStore.getFunctionTreeInfo()
    //预先加载功能树
    if (userStore.userInfo) {
      await functionTreeStore.getFunctionTreeInfo()
    }
    //   // 1. 提示用户
    ElMessage({ type: "success", message: "登录成功" })
    // 2. 跳转首页
    router.replace({ path: "/index", query: { f2ListId: "0" } })
  }
  fileReader.readAsDataURL(blob)
}
//登录
const loginByFace = async () => {
   await capture()
}

onMounted(() => {
  setupCamera()
})

onBeforeUnmount(()=> closeCamera())

</script>

<template>
  <div style="height:280px;">
    <video ref="videoRef" width="200" height="200"  autoplay></video>
    <div style="justify-content: center; width:320;;display: flex;margin-top: 10px;">
      <el-button class="subBtn" type="warning" size="large" icon="CameraFilled" @click="loginByFace">登录</el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.subBtn {
  background: $xtxColor;
  width: 90%;
  color: #fff;
}
</style>
